import {reactive, toRefs, watch} from "vue";
import TokenService from "./token.service.js";

const AUTH_KEY = 'testapi_token'
export const AUTH_TOKEN = 'access_token'

const state = reactive({
    authenticating: false,
    user: undefined,
    userData: undefined,
    error: undefined,
})

export const useAuth = () => {
    const setUser = (payload, remember) => {
        if ( remember ) {
            TokenService.setUser(payload)
        }

        state.user = payload
        state.error = undefined
    }

    const logout = () => {
        window.localStorage.removeItem('user')
        return Promise.resolve(state.user = undefined)
    }

    return {
        setUser,
        logout,
        ...toRefs(state),
    }
}
